package com.qy.dao.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.qy.dao.UserDao;
import com.qy.model.PageModel;

@Repository("userDao")
public class UserDaoImpl<T> implements UserDao<T> {
	@Autowired
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public void save(T t) {
		// TODO Auto-generated method stub
		hibernateTemplate.save(t);
	}

	@Override
	public List<T> select(String hql, Object[] object) throws Exception {
		// TODO Auto-generated method stub
		List<T> list = new ArrayList<>();
		list = (List<T>) hibernateTemplate.find(hql, object);
		return list;
	}

	@Override
	public void delete(T t) throws Exception {
		// TODO Auto-generated method stub
		hibernateTemplate.delete(t);
	}

	@Override//用来修改的方法
	public void execute(String hql, List<Object> list) throws Exception {
		// TODO Auto-generated method stub
		Query query =  hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
		for (int i = 0; i <list.size(); i++) {
			query.setParameter(i, list.get(i));
		}
		query.executeUpdate();
	}

	@Override
	public List<T> selectAllByPage(String hql, Object[] obj, PageModel page) throws Exception {
		// TODO Auto-generated method stub
		Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
		  Query query = session.createQuery(hql);
		  if(obj != null){
		   for(int i = 0; i < obj.length; i++){
		    query.setParameter(i, obj[i]);
		   }
		  }
		  if(page != null){
		   //设置每页显示条数
		   query.setMaxResults(page.getPageSize());
		   //设置从第几条开始显示
		   query.setFirstResult((page.getCurrentPage()-1)*page.getPageSize());
		  }
		  List<T> list = query.list();
		  return list;
	}

	@Override
	public String saveFile(String fileFileName,File file) throws IOException {
		// TODO Auto-generated method stub
		File file1 = new File("/Users/qingyun/Desktop/film/film/WebContent/images");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  String datePath = sdf.format(new Date());
		  File filepath = new File(file1+"/"+datePath);
		  if(!filepath.exists()){
			  filepath.mkdirs();
		  }
		  Long time = System.currentTimeMillis();
		  File filePath1 = new File(filepath+"/"+time+fileFileName);
		  FileUtils.copyFile(file, filePath1);
		  String url = "images/"+datePath+"/"+time+fileFileName;
		  return url;
	}
}
